package com.lfsenior.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by dlupan on 2018/10/31
 */
public class TopicReceiver {
    // TCP 地址
    public static final String BROKER_URL="tcp://localhost:61616";
    // 目标
    public static final String DESTINATION="TOPIC-QUEUE";

    public static void run() throws Exception{
        // 创建主题工厂
        TopicConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
        // 创建连接
        TopicConnection connection = factory.createTopicConnection();
        // 启动连接
        connection.start();
        // 创建session会话
        TopicSession session = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
        // 创建消息主题
        Topic topic = session.createTopic(DESTINATION);
        // 创建消息订阅
        TopicSubscriber subscriber = session.createSubscriber(topic);
        subscriber.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                MapMessage map = (MapMessage) message;
                try {
                    System.out.println(map.getLong("time")+"接收1#"+map.getString("text"));
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread.sleep(1000*5);

        // 提交会话
        session.commit();

        // 关闭相关
        session.close();
    }

    public static void main(String[] args) throws Exception{
        TopicReceiver.run();
    }
}